﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.EditorExt;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.GlobeCore;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using DIWAGIS.Modules;
using ESRI.ArcGIS.Carto;
namespace DIWAGIS.ApplicationLayer.EditorTools
{
    /// <summary>
    /// Summary description for ToolViewFeature.
    /// </summary>
    [Guid("45288024-4ab5-47d3-94e0-a906ccc45e61")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("DIWAGIS.ApplicationLayer.EditorTools.ToolViewFeature")]
    public sealed class ToolViewFeature : BaseTool
    {
        #region COM Registration Function(s)
        [ComRegisterFunction()]
        [ComVisible(false)]
        static void RegisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryRegistration(registerType);

            //
            // TODO: Add any COM registration code here
            //
        }

        [ComUnregisterFunction()]
        [ComVisible(false)]
        static void UnregisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryUnregistration(registerType);

            //
            // TODO: Add any COM unregistration code here
            //
        }

        #region ArcGIS Component Category Registrar generated code
        /// <summary>
        /// Required method for ArcGIS Component Category registration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryRegistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            ControlsCommands.Register(regKey);

        }
        /// <summary>
        /// Required method for ArcGIS Component Category unregistration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryUnregistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            ControlsCommands.Unregister(regKey);

        }

        #endregion
        #endregion
        private IPoint m_pPoint;
        private INewEnvelopeFeedback m_pFeedbackEnv;
        private Boolean flat = false;
        private IHookHelper m_hookHelper;

        public ToolViewFeature()
        {
            //
            // TODO: Define values for the public properties
            //
            base.m_category = ""; //localizable text 
            base.m_caption = "";  //localizable text 
            base.m_message = "";  //localizable text
            base.m_toolTip = "";  //localizable text
            base.m_name = "";   //unique id, non-localizable (e.g. "MyCategory_MyTool")
            try
            {
                //
                // TODO: change resource name if necessary
                //
                string bitmapResourceName = GetType().Name + ".png";
                base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
                base.m_cursor = new System.Windows.Forms.Cursor(GetType(), GetType().Name + ".cur");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
            }
        }

        #region Overridden Class Methods

        /// <summary>
        /// Occurs when this tool is created
        /// </summary>
        /// <param name="hook">Instance of the application</param>
        public override void OnCreate(object hook)
        {
            //if (m_hookHelper == null)
            //    m_hookHelper = new HookHelperClass();

            //m_hookHelper.Hook = hook;


            try
            {
                generalVariable.pHookHelper = new HookHelperClass();
                generalVariable.pHookHelper.Hook = hook;
                if (generalVariable.pHookHelper.ActiveView == null)
                {
                    generalVariable.pHookHelper = null;
                }
            }
            catch
            {
                generalVariable.pHookHelper = null;
            }

            if (generalVariable.pHookHelper == null)
                base.m_enabled = false;
            else
                base.m_enabled = true;

            // TODO:  Add other initialization code


            // TODO:  Add ToolViewFeature.OnCreate implementation
        }

        /// <summary>
        /// Occurs when this tool is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add ToolViewFeature.OnClick implementation
        }

        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolViewFeature.OnMouseDown implementation

            if (generalVariable.pHookHelper.ActiveView is IMap)
            {
                if (generalVariable.currentNameLayerWorking != null)
                {
                    IActiveView pActiveView;
                    pActiveView = (IActiveView)generalVariable.pHookHelper.FocusMap;

                    //Store current point, set mousedown flag
                    m_pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);

                    flat = true;

                }

                else
                {
                    //frm_message.showMesage("Vui lòng chọn lớp dữ liệu sẽ thao tác", 1);
                }
            }
        }

        public override void OnMouseMove(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolViewFeature.OnMouseMove implementation

            if (flat == true && generalVariable.pHookHelper.ActiveView is IMap)
            {

                IActiveView pActiveView;
                pActiveView = (IActiveView)generalVariable.pHookHelper.FocusMap;

                // ' Create a rubber banding box, if it hasn't been created already
                if (m_pFeedbackEnv == null)
                {
                    m_pFeedbackEnv = new NewEnvelopeFeedback();
                    m_pFeedbackEnv.Display = pActiveView.ScreenDisplay;
                    m_pFeedbackEnv.Start(m_pPoint);
                }

                //'Store current point, and use to move rubberband
                m_pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                m_pFeedbackEnv.MoveTo(m_pPoint);
            }

        }

        public override void OnMouseUp(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolViewFeature.OnMouseUp implementation

            IEnvelope pEnv;
            IActiveView pActiveView;
            IMap map;

            //If ActiveView is a PageLayout 
            if (generalVariable.pHookHelper.ActiveView is IPageLayout)
            {
                return;
            }
            else //Or ActiveView is a Map 
            {
                map = generalVariable.pHookHelper.FocusMap;
            }

            pActiveView = (IActiveView)generalVariable.pHookHelper.FocusMap;

            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

            if (m_pFeedbackEnv != null)
            {
                pEnv = m_pFeedbackEnv.Stop();
                generalVariable.pHookHelper.FocusMap.SelectByShape(pEnv, null, false);
            }
            else
            {
                generalVariable.pHookHelper.FocusMap.SelectByShape(m_pPoint, null, false);
            }

            //Refresh the selections
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

            /////////////////////////////////////////////////////////////////////////////////////////////////////////

            IFeatureSelection pFeatSel;
            ISelectionSet pSelectionSet;
            ICursor pCursor;
            IFeature pFeature;

            ILayer layer = null;
            // lấy layer muốn tìm feature 


            for (int i = 0; i < generalVariable.mapControl.LayerCount - 1; i++)
            {
                layer = generalVariable.mapControl.get_Layer(i);
                if (layer.Name == generalVariable.currentNameLayerWorking)
                {
                    break;
                }
            }

            if (layer == null)
            {
                return;
            }

            pFeatSel = (IFeatureSelection)layer;
            pSelectionSet = pFeatSel.SelectionSet;

            if (pSelectionSet.Count == 0)
            {
                //Reset rubberband and mousedown state
                m_pFeedbackEnv = null;
                flat = false;
                //frm_message.showMesage("Không có đối tượng nào trong lớp " + layer.Name + " được chọn", 1);

                generalVariable.pHookHelper.FocusMap.ClearSelection();
                //Get the IActiveView of the FocusMap
                IActiveView activeView = (IActiveView)generalVariable.pHookHelper.FocusMap;
                //Get the visible extent of the display
                IEnvelope bounds = activeView.ScreenDisplay.DisplayTransformation.FittedBounds;
                //Refresh the visible extent of the display
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, bounds);


                return;
            }

            pSelectionSet.Search(null, false, out pCursor);

            IFeatureCursor fCursor;

            fCursor = (IFeatureCursor)pCursor;
            pFeature = fCursor.NextFeature();

            if (pFeature == null)
            {
                generalVariable.pHookHelper.FocusMap.ClearSelection();
                //Get the IActiveView of the FocusMap
                IActiveView activeView = (IActiveView)generalVariable.pHookHelper.FocusMap;
                //Get the visible extent of the display
                IEnvelope bounds = activeView.ScreenDisplay.DisplayTransformation.FittedBounds;
                //Refresh the visible extent of the display
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, bounds);

                //Reset rubberband and mousedown state
                m_pFeedbackEnv = null;
                flat = false;
                return;
            }

            // xóa các feature khác 
            generalVariable.pHookHelper.FocusMap.ClearSelection();
            //Get the IActiveView of the FocusMap
            IActiveView _activeView = (IActiveView)generalVariable.pHookHelper.FocusMap;
            //Get the visible extent of the display
            IEnvelope _bounds = _activeView.ScreenDisplay.DisplayTransformation.FittedBounds;
            //Refresh the visible extent of the display
            _activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, _bounds);


            //chọn lại cái feature mới tìm thấy 
            map = generalVariable.pHookHelper.FocusMap;

            map.SelectFeature(layer, pFeature);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

            m_pFeedbackEnv = null;
            flat = false;

            // gọi hàm load form 
            ConfigInterface controller;
            controller = new ConfigInterface();
            controller.loadFormByLayerName("view", pFeature, null, layer);

        }
      
        #endregion


        public bool enabled
        {
            get
            {
                if (generalVariable.pHookHelper.FocusMap == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    }


}

